import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
// ===================================================================== Image
import Img_name from '@img/test-center/name.png'
// ===================================================================== Declare
const { $fn, $Lazy, $http, $config } = window
// ===================================================================== Lazy
const Page 			= $Lazy.load(()=>import('#tp/page/page-full'))
const Tabs 			= $Lazy.load(()=>import('#tp/tabs/tabs'))
const Image 		= $Lazy.load(()=>import('@antd/image'))
const Confirm 		= $Lazy.file(()=>import('@antd/common/confirm-submit'))
//
const HistoryModal 	= $Lazy.state(()=>import('./cpt/history-modal'))
// ===================================================================== data
const tabsData = [
	{ title:'历史', 	status:95 },
	{ title:'待批准', 	status:99 },
]
const def = 1
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		pag: {},
		selectedKeys: [],
		status: tabsData[def].status,
		// 搜索表单列表
		forms : [
			{ label: '姓名',	 name: 'name' },
			{ label: '接收时间',  names: ['start_at','end_at'], type:'date-range' },
		],
		hide: true
	}
	
	model = {}
	query = {}

	// 使用上次报告时间 默认为 否
	use_old_approve_at = 0
	
	componentDidMount(){
		let { spec_num, spec_code, project_id, audit } = $fn.query()
		
		if(+audit === 1){
			this.query = { status:tabsData[def].status }
		}else{
			this.query = { status:tabsData[def].status, spec_num }
		}
		
		if(project_id){
			this.query = { ...this.query, project_id }
		}
		
		const type = $config.getEnv()
		
		this.setState({ spec_num, type, selectedKeys:[spec_num] })
		
		this.getInfo({ id:spec_num, spec_code})
		this.fetch()
		
		const { reportUrl, reportPath } = window.globalConfig
		if(type === 2){ // 预览增加验证 2022-1-20 6:09:10 ?F10: PM? --伍智睿
			$http.submit(null,'index/getReportSign', { param:{spec_num}, isPull:true }).then(({sign})=>{
				$http.submit(null, reportPath + '/token', { param:{token:sign}, isPull:true }).then(token=>{
					this.setState({reportUrl: `${reportUrl}&token=${token}`})
				})
			})
		}else{
			this.setState({reportUrl: `${reportUrl}`})
		}
		// window.$fn.fresh.backRefresh('onModelRefresh','clear-keys-info')
		
	}
	createIframe = spec_num => {
		const box = document.querySelector('#iframe')
		let _iframe = box.querySelector('iframe')
		const type = $config.getEnv()
		if(!_iframe){
			_iframe = document.createElement('iframe')
			_iframe.className = 'abs_full wh'
			box.appendChild(_iframe)
			
		}
		
		_iframe.src = `${$config.reportUrl(type)}&rno=${spec_num}&type=${type}`
	}
	// paging
	fetch = () => $fn.fetch.call(this,'kd-report-spec/reportInfo' )
	//
	getInfo = ({id, spec_code}) => {
		// 获取报告单信息
		$http.submit(null,'kd-report-spec/reportDetails', { param:{ spec_num: id, spec_code }, isPull:true, }).then(data=>{
			// iframe 的加载放在 reportDetails 接口之后 2021-9-13 4:00:28 ?F10: PM? --伍智睿
			this.setState({
				selectedRows: [{...data, spec_num: data.id }],
				report_path: data.report_path
			}, () => this.setState({ hide:false }))
		})
	}
	
	// 表单
	cols = [
		{ title: '标本条码',			dataIndex: 'spec_code', 	sorter:true,	...$fn.table.spec_code },
		{ title: '姓名', 			dataIndex: 'name', 			sorter:true,	...$fn.table.name, render: (text, { check_same_name }) => {
			return +check_same_name === 1 ? <div className='fxm'><img src={Img_name} alt='' style={{width:16, marginRight:2}}/><span>{text}</span></div> : text
		} },
		{ title: '实验号', 			dataIndex: 'experiment_num', sorter:true,	width:150 },
	]
	
	// tabs 操作按钮
	controls = () => {
		const { pagingLoading, selectedRows, selectedKeys, data, status, backRrefsh } = this.state
		return [
			{ type: 'checkbox', label: '使用上次报告时间', isNumber: true, onChange: value =>{
				this.use_old_approve_at = value
			} },
			// 新增岗位ID参数 20211020 耿琰
			Controls.click.call(this,'查看同名历史记录', ()=>this.historyModal.open(selectedRows[0], this.query.project_id), { isKeys:true }),
			{ label:'批准报告单', loading:pagingLoading, hide: status !== tabsData[def].status, disabled: !$fn.hasArray(selectedKeys), onClick:()=>{
				Confirm.then(f=>{
					const { child_spec_code, spec_num } = selectedRows[0] || {}
					f.call(null,'kd-report-spec/reportExamine', { title:'批准报告单', param: { spec_code: child_spec_code, spec_num, use_old_approve_at: this.use_old_approve_at }, onOk: async ()=>{
						// 查找当前数据索引
						let index = data.findIndex( v => v['id'] ===  spec_num )
						// 跳转到下一个条码
						const _data = await this.fetch()
						const _rows = _data[index]
						
						if(_rows){
							this.setState({ spec_num: _rows.id,  selectedKeys:[_rows.id], selectedRows:[{..._rows, spec_num: _rows.id}], hide:true })
							// iframe 的加载放在 reportDetails 接口之后 2021-9-13 4:00:28 ?F10: PM? --伍智睿
							this.getInfo(_rows)
						}
						this.setState({ backRrefsh:true })
					}})
				})
			} },
			Controls.back.call(this,{ refresh:backRrefsh, refreshName:'onModelRefresh', param:'clear-keys-info' })
		]
	}
	
	render(){
		const { report_path, hide, reportUrl, spec_num, type } = this.state
		let PreviewComponent = null
		if(report_path){
			PreviewComponent = report_path.indexOf('pdf') !== -1 ? <iframe title='预览报告单' className='abs_full wh' src={$fn.getImagePrefix(report_path)} />: <Image className='wh' src={report_path}/>
		}else{
			PreviewComponent = reportUrl ? <iframe title='预览报告单' className='abs_full wh' src={`${reportUrl}&rno=${spec_num}&type=${type}`} /> : <div className='f16 g9'>获取数据失败，请刷新页面</div>
		}
		return (
			<>
				<Page className='fx'>
					<div className='fv pb10' style={{width:'40%'}}>
						{/* 选项卡 */}
						<Tabs
							data			 =	{ tabsData }
							defaultActiveKey =  { def }
							onTabs 			 = { ({ status }, index) => {
								this.setState({ status })
								this.model.status = status
								this.fetch({ status })
							}}
							controls = { this.controls() }
						/>
						{/* 搜索 */}
						{ SearchForm.call(this, { labelWidth:'s4' }) }
						{/* 表格 */}
						{ 
							Table.call(this, { type:1, idStr:'id', sort:true, onSelect: (selectedKeys, selectedRows)=>{
									this.setState({ spec_num: selectedKeys[0], selectedKeys, selectedRows, hide:true })
									// iframe 的加载放在 reportDetails 接口之后 2021-9-13 4:00:28 ?F10: PM? --伍智睿
									this.getInfo(selectedRows[0])
								}
							})
						}
					</div>
					<div className='ex rel fxmc' style={{background:'#f5f5f5'}}>
						{
							!hide ? PreviewComponent : <div className='f16 g9'>报告单加载...</div>
						}
					</div>
				</Page>
				<HistoryModal onRef={ ref => this.historyModal = ref } />
			</>
		)
	}
}

export default Index